from sqlalchemy.orm import Session
from schema import Sensor_schema
from model import Sensor_model



def get_Sensor(db: Session, ID: int):
    return db.query(Sensor_model.Sensor).filter(Sensor_model.Sensor.ID == ID).first()


def get_all_Sensor(db: Session):
    return db.query(Sensor_model.Sensor).all()


def delete_Sensor(db: Session, ID):
    to_delete = db.query(Sensor_model.Sensor).filter(Sensor_model.Sensor.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Sensor(db: Session, Sensor: Sensor_schema.Sensor):
    db_Sensor = Sensor_model.Sensor(
        SensorNumber=Sensor.SensorNumber,
        SensorType=Sensor.SensorType,
        NetworkAddress=Sensor.NetworkAddress,
        IndicatorNamesJSON=Sensor.IndicatorNamesJSON,
        OnlineStatus=Sensor.OnlineStatus,
    )
    db.add(db_Sensor)
    db.commit()
    db.refresh(db_Sensor)
    return db_Sensor


def update_Sensor(db: Session, ID, field_name, new_value):
    db_Sensor = db.query(Sensor_model.Sensor).filter(Sensor_model.Sensor.ID == ID).first()
    setattr(db_Sensor, field_name, new_value)
    db.commit()
    db.refresh(db_Sensor)
    return db_Sensor
